from django.shortcuts import render
from django.utils import timezone

# Create your views here.
from rest_framework.response import Response

from rest_framework import viewsets
from .models import User
from .serializers import UsersSerializer
from django.conf import settings
import jwt
import datetime
# from django.contrib.auth import authenticate    # 使用 Django 自带的用户密码校验方法


class UsersViewset(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UsersSerializer

    def destroy(self, request, *args, **kwargs):
        pk = request.parser_context["kwargs"]["pk"]
        try:
            obj = User.objects.filter(pk=pk)
            if obj:
                username = obj.first().username
                obj.delete()
                return Response({"msg": f"{username}用户已经删除"}, status=204)
            return Response({"msg": "未找到用户"}, status=200)
        except Exception as e:
            # print(f"obj{obj}")
            return Response({"msg": f"删除用户失败：{e}"}, status=400)
'''
    登录接口，验证用户密码及生成 token
'''
class LoginViewset(viewsets.ViewSet,
                   viewsets.mixins.UpdateModelMixin,
                   viewsets.mixins.CreateModelMixin):
    authentication_classes = []
    def create(self, request, *args, **kwargs):
        data = request.data
        print(f'username:{data["username"]}，password:{data["password"]}')
        ## 判断是否有传入 username 和 password 字段
        field_name = self.check_field(data)
        if not field_name:
            return Response({"msg": "必须传入 username or password"})

        user_obj = User.objects.filter(username=data['username'])
        if not user_obj:
            user_obj = User.objects.filter(email=data['username'])

        if not user_obj:
            return Response({"msg": f"{field_name} 用户不存在"})

        ## 验证用户名密码
        if (data['username'] == user_obj.first().username or data['username'] == user_obj.first().email) and data[
            'password'] == user_obj.first().password:
            user_obj.update(last_login=timezone.now())
            # return Response({"msg": f"{user_obj.first().username} 用户登录成功"})

            """
            1、如果用户密码验证成功，就返回 token、菜单权限、接口权限
            """
            slat = settings.SECRET_KEY

            # 构造header
            headers = {
                'type': 'jwt',
                'alg': 'HS256'
            }

            # 构造payload
            payload = {
                'username': data['username'],  # 自定义用户名
                'exp': datetime.datetime.now(tz=timezone.utc) + datetime.timedelta(minutes=60)  # 超时时间
            }

            token = jwt.encode(payload=payload, key=slat, algorithm='HS256', headers=headers)

            """
            菜单权限
            """
            menus = user_obj.all().values("groups__menus__firstmenu", "groups__menus__secondmenu__secondmenu",
                                 "groups__menus__secondmenu__routename")

            # 重组数据
            formatted_data = []
            for item in menus:
                if item["groups__menus__firstmenu"] != None:
                    title = item.pop('groups__menus__firstmenu')
                    # 从字典中移除title，剩下的作为子菜单项
                    sub_menu_item = {
                        'name': item.pop('groups__menus__secondmenu__secondmenu'),
                        'route': item.pop('groups__menus__secondmenu__routename')
                    }

                    # 查找或创建对应的一级菜单项
                    menu_item = next((menu for menu in formatted_data if menu['title'] == title), None)
                    if menu_item:
                        # 如果一级菜单已存在，则添加到其value列表中
                        menu_item['value'].append(sub_menu_item)
                    else:
                        # 否则，创建新的菜单项
                        formatted_data.append({'title': title, 'value': [sub_menu_item]})

            """
            接口权限
            """
            intPer = user_obj.all().values_list("groups__interfacepaths__name", flat=True)

            data = {"token": token, "menulist": formatted_data, "interfacepermission": intPer, "username": data['username']}

            return Response({'type': 'success', 'msg': "用户登录成功", "data": data})

        return Response({"msg": f"{field_name} 密码不正确"})

    def update(self, request, *args, **kwargs):
        pass

    def check_field(self, data):
        if 'username' in data and 'password' in data:
            return True
        else:
            return False


# class LoginViewset(viewsets.ModelViewSet):
#     queryset = Users.objects.all()
#     serializer_class = LoginSerializer
#
#     def create(self, request, *args, **kwargs):
#         # instance = self.get_object()
#         serializer = self.get_serializer(data=request.data)
#
#         if serializer.is_valid():
#             # print(serializer.data, type(serializer.data))
#             login_name = self.judgeUsername(serializer.data)
#             print(login_name)
#             if request.data[login_name] == 'username':
#                 user_obj = Users.objects.filter(username=request.data["username"])
#             else:
#                 user_obj = Users.objects.filter(email=request.data["email"])
#             if user_obj:
#                 print("找到用户了")
#             # if request.data[login_name] == :
#
#
#         return Response(serializer.errors, status=400)
#
#     ## 判断表单传过来的是 username 字段还是 email 字段
#     def judgeUsername(self, serializer):
#         if 'username' in serializer:
#             return 'username'
#         elif 'email' in serializer:
#             return 'email'
#     '''
#         这种更新方法在提交表单时，还是要提交所有必填字段，否则提交表单时会校验不通过
#     '''
#     # def update(self, request, *args, **kwargs):
#     #     ## 从 kwargs 中获取 partial 标志，True 即为 patch，False 即为 put
#     #     partial = kwargs.pop('partial', False)
#     #     instance = self.get_object()
#     #     serializer = self.get_serializer(instance, data=request.data, partial=partial)
#     #
#     #
#     #     # 在这里手动控制校验逻辑，跳过特定字段
#     #     if serializer.is_valid():
#     #         # 假设我们要跳过'field_to_skip'字段的校验
#     #         validated_data = serializer.validated_data
#     #         validated_data = serializer.skip_field_validation(validated_data, ['phone', 'email'])
#     #
#     #
#     #         # 更新实例，此时已移除了需要跳过的字段
#     #         self.perform_update(serializer)
#     #
#     #         if getattr(instance, '_prefetched_objects_cache', None):
#     #             # If 'prefetch_related' has been applied to a queryset, we need to
#     #             # forcibly invalidate the prefetch cache on the instance.
#     #             instance._prefetched_objects_cache = {}
#     #
#     #         return Response(serializer.data)
#     #     else:
#     #         return Response(serializer.errors, status=400)
#
#     '''
#         使用这种强制部分更新
#     '''
#     def update(self, request, *args, **kwargs):
#         print(request.data)
#         partial = True  # 强制部分更新模式
#         instance = self.get_object()
#         serializer = self.get_serializer(instance, data=request.data, partial=partial)
#
#         if serializer.is_valid():
#             print(serializer)
#             # self.perform_update(serializer)
#             if getattr(instance, '_prefetched_objects_cache', None):
#                 instance._prefetched_objects_cache = {}
#             return Response(serializer.data)
#         else:
#             return Response(serializer.errors, status=400)


## 登录接口




